package com.nnnu.wsnackshop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nnnu.wsnackshop.config.NotificationWebSocketHandler;
import com.nnnu.wsnackshop.exception.ObjectException;
import com.nnnu.wsnackshop.mapper.*;
import com.nnnu.wsnackshop.pojo.dto.DeliveryDTO;
import com.nnnu.wsnackshop.pojo.dto.OrderCreateDTO;
import com.nnnu.wsnackshop.pojo.dto.OrderPageQueryDTO;
import com.nnnu.wsnackshop.pojo.entity.*;
import com.nnnu.wsnackshop.pojo.entity.UserCoupons;
import com.nnnu.wsnackshop.pojo.vo.*;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import com.nnnu.wsnackshop.config.RabbitMQConfig;
import com.nnnu.wsnackshop.pojo.dto.InventoryChangeDTO;
import org.springframework.beans.factory.annotation.Value;
import com.nnnu.wsnackshop.service.IUserCouponsService;
import com.nnnu.wsnackshop.service.IRidersService;
import com.nnnu.wsnackshop.service.IMembersService;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    private final ApplicationContext applicationContext;
    private final OrdersMapper ordersMapper;
    private final OrderItemsMapper orderItemsMapper;
    private final CartItemsMapper cartItemsMapper;
    private final ProductsMapper productsMapper;
    private final ProductSkuMapper productSkuMapper;
    private final AddressesMapper addressesMapper;
    private final CouponsMapper couponsMapper;
    private final DeliveriesMapper deliveriesMapper;
    private final RabbitTemplate rabbitTemplate;
    private final IUserCouponsService userCouponsService;
    private final IRidersService ridersService;
    private final StoreAddressesMapper storeAddressesMapper;
    private final IMembersService membersService;
    private final ReviewsMapper reviewsMapper;

    @Value("${spring.rabbitmq.enabled:false}")
    private boolean rabbitMqEnabled;

    private IOrdersService self;

    public OrdersServiceImpl(OrdersMapper ordersMapper, OrderItemsMapper orderItemsMapper,
            CartItemsMapper cartItemsMapper, ProductsMapper productsMapper,
            ProductSkuMapper productSkuMapper, AddressesMapper addressesMapper,
            CouponsMapper couponsMapper,
            DeliveriesMapper deliveriesMapper, RabbitTemplate rabbitTemplate,
            IUserCouponsService userCouponsService, IRidersService ridersService,
            StoreAddressesMapper storeAddressesMapper, IMembersService membersService,
            ApplicationContext applicationContext, ReviewsMapper reviewsMapper) {
        this.ordersMapper = ordersMapper;
        this.orderItemsMapper = orderItemsMapper;
        this.cartItemsMapper = cartItemsMapper;
        this.productsMapper = productsMapper;
        this.productSkuMapper = productSkuMapper;
        this.addressesMapper = addressesMapper;
        this.couponsMapper = couponsMapper;
        this.deliveriesMapper = deliveriesMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.userCouponsService = userCouponsService;
        this.ridersService = ridersService;
        this.storeAddressesMapper = storeAddressesMapper;
        this.membersService = membersService;
        this.applicationContext = applicationContext;
        this.reviewsMapper = reviewsMapper;
    }

    // 在初始化后获取代理对象
    @PostConstruct
    public void init() {
        // 获取Spring容器中的代理对象
        self = applicationContext.getBean(IOrdersService.class);
    }

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 超时未支付订单自动取消的时间窗口（分钟）
    private static final int AUTO_CANCEL_TIMEOUT_MINUTES = 10;

    // 自动确认收货的超时时间（天）
    private static final int AUTO_CONFIRM_RECEIPT_DAYS = 7;

    /**
     * 同步扣减商品库存
     *
     * @param skuId    商品规格ID
     * @param quantity 扣减数量
     * @return 扣减是否成功
     */
    private boolean deductInventorySynchronously(Integer skuId, Integer quantity) {

        // 使用乐观锁方式更新库存，防止超卖
        boolean updateSuccess = false;
        int retryCount = 0;

        while (!updateSuccess && retryCount < 3) {
            // 查询当前库存
            ProductSku sku = productSkuMapper.selectById(skuId);
            if (sku == null) {
                return false;
            }

            // 检查库存是否充足
            if (sku.getStock() < quantity) {
                return false;
            }

            // 计算新库存
            int newStock = sku.getStock() - quantity;

            // 使用乐观锁更新库存
            LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductSku::getId, skuId)
                    .eq(ProductSku::getStock, sku.getStock()) // 乐观锁条件：当前库存等于查询时的库存
                    .set(ProductSku::getStock, newStock);

            int updateResult = productSkuMapper.update(null, updateWrapper);
            // MyBatis-Plus在某些情况下可能返回一个很大的负数作为结果
            // 这里我们检查结果是否不等于0，而不是判断是否大于0
            updateSuccess = updateResult != 0;

            retryCount++;

            if (!updateSuccess && retryCount < 3) {
                log.info("库存更新失败，准备重试: skuId={}, 重试次数={}", skuId, retryCount);
                try {
                    // 短暂休眠后重试
                    Thread.sleep(100 + retryCount * 50L); // 随着重试次数增加等待时间
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("库存扣减被中断", e);
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 同步恢复商品库存
     *
     * @param skuId    商品规格ID
     * @param quantity 恢复数量
     * @return 恢复是否成功
     */
    private boolean restoreInventorySynchronously(Integer skuId, Integer quantity) {
        log.info("开始同步恢复库存: skuId={}, 恢复数量={}", skuId, quantity);

        // 使用乐观锁方式更新库存
        boolean updateSuccess = false;
        int retryCount = 0;

        while (!updateSuccess && retryCount < 3) {
            // 查询当前库存
            ProductSku sku = productSkuMapper.selectById(skuId);
            if (sku == null) {
                log.warn("商品规格不存在，无法恢复库存, skuId: {}", skuId);
                return false;
            }

            // 计算新库存
            int newStock = sku.getStock() + quantity;

            // 使用乐观锁更新库存
            LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProductSku::getId, skuId)
                    .eq(ProductSku::getStock, sku.getStock()) // 乐观锁条件：当前库存等于查询时的库存
                    .set(ProductSku::getStock, newStock);

            int updateResult = productSkuMapper.update(null, updateWrapper);
            updateSuccess = updateResult != 0;

            retryCount++;

            if (!updateSuccess && retryCount < 3) {
                try {
                    // 短暂休眠后重试
                    Thread.sleep(100 + retryCount * 50L); // 随着重试次数增加等待时间
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("库存恢复被中断", e);
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public OrderPreviewVO previewOrderFromCartItems(Integer userId, String cartItemIds) {
        if (StrUtil.isEmpty(cartItemIds)) {
            throw new ObjectException("购物车商品ID不能为空");
        }

        List<Integer> cartItemIdList = Arrays.stream(cartItemIds.split(",")).map(Integer::parseInt)
                .collect(Collectors.toList());

        // 查询购物车商品
        LambdaQueryWrapper<CartItems> cartQueryWrapper = new LambdaQueryWrapper<>();
        cartQueryWrapper.eq(CartItems::getUserId, userId).in(CartItems::getId, cartItemIdList);
        List<CartItems> cartItemsList = cartItemsMapper.selectList(cartQueryWrapper);

        if (cartItemsList.isEmpty()) {
            throw new ObjectException("购物车商品不存在");
        }

        // 获取所有商品ID和规格ID
        List<Integer> productIds = cartItemsList.stream().map(CartItems::getProductId).collect(Collectors.toList());

        List<Integer> skuIds = cartItemsList.stream().map(CartItems::getSkuId).collect(Collectors.toList());

        // 查询商品信息
        LambdaQueryWrapper<Products> productQueryWrapper = new LambdaQueryWrapper<>();
        productQueryWrapper.in(Products::getId, productIds);
        List<Products> productsList = productsMapper.selectList(productQueryWrapper);
        Map<Integer, Products> productsMap = productsList.stream()
                .collect(Collectors.toMap(Products::getId, Function.identity()));

        // 查询规格信息
        LambdaQueryWrapper<ProductSku> skuQueryWrapper = new LambdaQueryWrapper<>();
        skuQueryWrapper.in(ProductSku::getId, skuIds);
        List<ProductSku> skuList = productSkuMapper.selectList(skuQueryWrapper);
        Map<Integer, ProductSku> skuMap = skuList.stream()
                .collect(Collectors.toMap(ProductSku::getId, Function.identity()));

        // 构建商品列表
        List<OrderItemVO> items = cartItemsList.stream().map(cartItem -> {
            OrderItemVO itemVO = new OrderItemVO();

            Products product = productsMap.get(cartItem.getProductId());
            if (product == null) {
                throw new ObjectException("商品不存在");
            }

            ProductSku sku = skuMap.get(cartItem.getSkuId());
            if (sku == null) {
                throw new ObjectException("商品规格不存在");
            }

            // 验证库存
            if (sku.getStock() < cartItem.getQuantity()) {
                throw new ObjectException("商品[" + product.getName() + "]库存不足");
            }

            // 设置商品信息
            ProductSimpleVO productSimpleVO = new ProductSimpleVO();
            productSimpleVO.setId(product.getId());
            productSimpleVO.setName(product.getName());
            productSimpleVO.setImage(product.getMainImage());
            productSimpleVO.setCategoryId(product.getCategoryId());
            itemVO.setProduct(productSimpleVO);

            // 设置规格信息
            ProductSkuVO skuVO = new ProductSkuVO();
            skuVO.setId(sku.getId());
            skuVO.setProductId(sku.getProductId());
            skuVO.setSkuCode(sku.getSkuCode());
            skuVO.setSkuName(sku.getTitle());
            skuVO.setSpecs(sku.getSpecSnCombination());
            skuVO.setPrice(sku.getPrice());
            skuVO.setOriginalPrice(sku.getPrice());
            skuVO.setStock(sku.getStock());
            itemVO.setSku(skuVO);

            // 设置其他信息
            itemVO.setQuantity(cartItem.getQuantity());
            itemVO.setSubtotal(sku.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));

            return itemVO;
        }).collect(Collectors.toList());

        // 查询用户默认地址
        LambdaQueryWrapper<Addresses> addressQueryWrapper = new LambdaQueryWrapper<>();
        addressQueryWrapper.eq(Addresses::getUserId, userId).eq(Addresses::getIsDefault, 1);
        Addresses defaultAddress = addressesMapper.selectOne(addressQueryWrapper);

        // 如果没有默认地址，查询最新地址
        if (defaultAddress == null) {
            addressQueryWrapper = new LambdaQueryWrapper<>();
            addressQueryWrapper.eq(Addresses::getUserId, userId).orderByDesc(Addresses::getCreatedAt).last("LIMIT 1");
            defaultAddress = addressesMapper.selectOne(addressQueryWrapper);
        }

        AddressVO addressVO = null;
        if (defaultAddress != null) {
            addressVO = new AddressVO();
            BeanUtils.copyProperties(defaultAddress, addressVO);
            // 手动设置字段映射
            addressVO.setRecipientName(defaultAddress.getRecipient());
            addressVO.setRecipientPhone(defaultAddress.getPhone());
            addressVO.setDetailAddress(defaultAddress.getDetail());
        }

        // 计算总金额
        BigDecimal goodsAmount = items.stream().map(OrderItemVO::getSubtotal).reduce(BigDecimal.ZERO, BigDecimal::add);

        // 构建订单预览VO
        OrderPreviewVO previewVO = new OrderPreviewVO();
        previewVO.setItems(items);
        previewVO.setAddress(addressVO);
        previewVO.setGoodsAmount(goodsAmount);

        // 根据配送方式计算运费
        BigDecimal deliveryFee;
        // 默认为同城配送
        // 同城配送，收取3元运费
        deliveryFee = BigDecimal.valueOf(3);

        previewVO.setDeliveryFee(deliveryFee);
        previewVO.setDiscountAmount(BigDecimal.ZERO); // 默认无优惠
        previewVO.setTotalAmount(goodsAmount.add(previewVO.getDeliveryFee()).subtract(previewVO.getDiscountAmount()));

        // 查询可用优惠券列表（应根据用户已领取且未使用的券）
        List<CouponVO> allCoupons = userCouponsService.getUserAvailableCoupons(userId);
        List<CouponVO> availableCoupons = allCoupons.stream()
                .filter(coupon -> coupon.getMinAmount() == null || goodsAmount.compareTo(coupon.getMinAmount()) >= 0)
                .collect(Collectors.toList());
        previewVO.setAvailableCoupons(availableCoupons);

        return previewVO;
    }

    @Override
    public OrderPreviewVO previewOrderFromProduct(Integer userId, Integer productId, Integer skuId, Integer quantity) {
        log.info("开始预览直接购买订单: userId={}, productId={}, skuId={}, quantity={}",
                userId, productId, skuId, quantity);

        // 查询商品信息
        Products product = productsMapper.selectById(productId);
        if (product == null) {
            throw new ObjectException("商品不存在");
        }
        log.info("商品信息: id={}, name={}, mainImage={}", product.getId(), product.getName(), product.getMainImage());

        // 查询规格信息
        ProductSku sku = productSkuMapper.selectById(skuId);
        if (sku == null) {
            throw new ObjectException("商品规格不存在");
        }
        log.info("规格信息: id={}, skuCode={}, title={}, price={}, stock={}",
                sku.getId(), sku.getSkuCode(), sku.getTitle(), sku.getPrice(), sku.getStock());

        // 验证库存
        if (sku.getStock() < quantity) {
            throw new ObjectException("商品库存不足");
        }
        log.info("库存验证通过: 当前库存={}, 购买数量={}", sku.getStock(), quantity);

        // 构建商品列表
        List<OrderItemVO> items = new ArrayList<>();
        OrderItemVO itemVO = new OrderItemVO();

        // 设置商品信息
        ProductSimpleVO productSimpleVO = new ProductSimpleVO();
        productSimpleVO.setId(product.getId());
        productSimpleVO.setName(product.getName());
        productSimpleVO.setImage(product.getMainImage());
        productSimpleVO.setCategoryId(product.getCategoryId());
        itemVO.setProduct(productSimpleVO);

        // 设置规格信息
        ProductSkuVO skuVO = new ProductSkuVO();
        skuVO.setId(sku.getId());
        skuVO.setProductId(sku.getProductId());
        skuVO.setSkuCode(sku.getSkuCode());
        skuVO.setSkuName(sku.getTitle());
        skuVO.setSpecs(sku.getSpecs());
        skuVO.setPrice(sku.getPrice());
        skuVO.setOriginalPrice(sku.getOriginalPrice());
        skuVO.setStock(sku.getStock());
        itemVO.setSku(skuVO);

        // 设置其他信息
        itemVO.setQuantity(quantity);
        BigDecimal subtotal = sku.getPrice().multiply(new BigDecimal(quantity));
        itemVO.setSubtotal(subtotal);

        log.info("设置商品数量和小计: quantity={}, price={}, subtotal={}",
                quantity, sku.getPrice(), subtotal);

        items.add(itemVO);

        // 查询用户默认地址
        LambdaQueryWrapper<Addresses> addressQueryWrapper = new LambdaQueryWrapper<>();
        addressQueryWrapper.eq(Addresses::getUserId, userId).eq(Addresses::getIsDefault, 1);
        Addresses defaultAddress = addressesMapper.selectOne(addressQueryWrapper);

        // 如果没有默认地址，查询最新地址
        if (defaultAddress == null) {
            addressQueryWrapper = new LambdaQueryWrapper<>();
            addressQueryWrapper.eq(Addresses::getUserId, userId).orderByDesc(Addresses::getCreatedAt).last("LIMIT 1");
            defaultAddress = addressesMapper.selectOne(addressQueryWrapper);
        }

        AddressVO addressVO = null;
        if (defaultAddress != null) {
            addressVO = new AddressVO();
            BeanUtils.copyProperties(defaultAddress, addressVO);
            // 手动设置字段映射
            addressVO.setRecipientName(defaultAddress.getRecipient());
            addressVO.setRecipientPhone(defaultAddress.getPhone());
            addressVO.setDetailAddress(defaultAddress.getDetail());
        }

        // 计算总金额
        BigDecimal goodsAmount = items.stream().map(OrderItemVO::getSubtotal).reduce(BigDecimal.ZERO, BigDecimal::add);

        // 构建订单预览VO
        OrderPreviewVO previewVO = new OrderPreviewVO();
        previewVO.setItems(items);
        previewVO.setAddress(addressVO);
        previewVO.setGoodsAmount(goodsAmount);

        // 根据配送方式计算运费
        BigDecimal deliveryFee;
        // 同城配送，收取3元运费
        deliveryFee = BigDecimal.valueOf(3);

        previewVO.setDeliveryFee(deliveryFee);
        previewVO.setDiscountAmount(BigDecimal.ZERO); // 默认无优惠
        previewVO.setTotalAmount(goodsAmount.add(previewVO.getDeliveryFee()).subtract(previewVO.getDiscountAmount()));

        // 查询可用优惠券列表（应根据用户已领取且未使用的券）
        List<CouponVO> allCoupons = userCouponsService.getUserAvailableCoupons(userId);
        List<CouponVO> availableCoupons = allCoupons.stream()
                .filter(coupon -> coupon.getMinAmount() == null || goodsAmount.compareTo(coupon.getMinAmount()) >= 0)
                .collect(Collectors.toList());
        previewVO.setAvailableCoupons(availableCoupons);

        return previewVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVO createOrder(Integer userId, @NotNull OrderCreateDTO orderCreateDTO) {
        log.info("开始创建订单: userId={}, orderData={}", userId, orderCreateDTO);

        // 验证地址
        Addresses address = addressesMapper.selectById(orderCreateDTO.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            throw new ObjectException("收货地址不存在");
        }

        // 准备商品数据
        List<OrderItemVO> itemVOList;
        List<Integer> cartItemIds = new ArrayList<>();

        if (orderCreateDTO.getCartItemIds() != null && !orderCreateDTO.getCartItemIds().isEmpty()) {
            // 从购物车创建订单
            String[] cartItemIdArray = orderCreateDTO.getCartItemIds().split(",");
            for (String cartItemId : cartItemIdArray) {
                cartItemIds.add(Integer.parseInt(cartItemId));
            }
            log.info("从购物车创建订单: cartItemIds={}", cartItemIds);

            // 查询购物车商品
            OrderPreviewVO previewVO = self.previewOrderFromCartItems(userId, orderCreateDTO.getCartItemIds());
            itemVOList = previewVO.getItems();
        } else if (orderCreateDTO.getProductId() != null && orderCreateDTO.getSkuId() != null
                && orderCreateDTO.getQuantity() != null) {
            // 直接购买
            log.info("直接购买创建订单: productId={}, skuId={}, quantity={}",
                    orderCreateDTO.getProductId(), orderCreateDTO.getSkuId(), orderCreateDTO.getQuantity());

            OrderPreviewVO previewVO = self.previewOrderFromProduct(userId, orderCreateDTO.getProductId(),
                    orderCreateDTO.getSkuId(), orderCreateDTO.getQuantity());
            itemVOList = previewVO.getItems();
        } else {
            throw new ObjectException("参数错误");
        }

        // 记录商品项信息
        log.info("订单包含{}个商品项", itemVOList.size());
        for (int i = 0; i < itemVOList.size(); i++) {
            OrderItemVO item = itemVOList.get(i);
            log.info("商品项#{}: 商品ID={}, 商品名称={}, 规格ID={}, 数量={}",
                    i + 1, item.getProduct().getId(), item.getProduct().getName(),
                    item.getSku().getId(), item.getQuantity());
        }

        // 检查优惠券
        UserCoupons userCoupon = null;
        if (orderCreateDTO.getCouponId() != null) {
            userCoupon = userCouponsService.getById(orderCreateDTO.getCouponId());
            if (userCoupon == null || !userCoupon.getUserId().equals(userId) || userCoupon.getStatus() != 0) {
                log.error("未找到用户可用的优惠券: userId={}, userCouponId={}", userId, orderCreateDTO.getCouponId());
                throw new ObjectException("该优惠券不可用，请刷新后重试");
            }
            // 校验券模板有效性
            Coupons coupon = couponsMapper.selectById(userCoupon.getCouponId());
            if (coupon == null) {
                throw new ObjectException("优惠券不存在");
            }
            // 计算商品总金额
            BigDecimal goodsAmount = itemVOList.stream().map(OrderItemVO::getSubtotal).reduce(BigDecimal.ZERO,
                    BigDecimal::add);
            if (coupon.getMinAmount().compareTo(goodsAmount) > 0) {
                throw new ObjectException("订单金额未达到优惠券使用条件");
            }
            LocalDateTime now = LocalDateTime.now();
            if (coupon.getStartTime().isAfter(now)) {
                throw new ObjectException("优惠券尚未生效，生效时间：" + coupon.getStartTime().format(DATE_TIME_FORMATTER));
            }
            if (coupon.getEndTime().isBefore(now)) {
                throw new ObjectException("优惠券已过期，过期时间：" + coupon.getEndTime().format(DATE_TIME_FORMATTER));
            }
        }

        // 创建订单
        Orders order = new Orders();
        order.setUserId(userId);
        order.setOrderNo(generateOrderNo());
        order.setPayStatus(0); // 待付款
        order.setAddressId(orderCreateDTO.getAddressId());

        // 设置门店ID
        if (orderCreateDTO.getStoreId() != null) {
            // 如果前端传了门店ID，直接使用
            order.setStoreId(orderCreateDTO.getStoreId());
        } else if ("self".equals(orderCreateDTO.getDeliveryType())) {
            // 如果是自提，但没有指定门店，则抛出异常
            throw new ObjectException("自提订单必须选择门店");
        } else {
            // 如果不是自提且没有指定门店，抛出异常
            throw new ObjectException("请选择门店");
        }

        // 计算商品总金额
        BigDecimal goodsAmount = itemVOList.stream().map(OrderItemVO::getSubtotal).reduce(BigDecimal.ZERO,
                BigDecimal::add);

        // 计算优惠金额
        BigDecimal discountAmount = BigDecimal.ZERO;
        if (userCoupon != null) {
            Coupons coupon = couponsMapper.selectById(userCoupon.getCouponId());
            if (coupon != null) {
                if ("amount".equals(coupon.getType())) {
                    discountAmount = coupon.getAmount();
                } else if ("percentage".equals(coupon.getType())) {
                    BigDecimal discountRate = coupon.getAmount();
                    discountAmount = goodsAmount.multiply(BigDecimal.ONE.subtract(discountRate)).setScale(2,
                            RoundingMode.HALF_UP);
                }
                order.setCouponId(coupon.getId());
            }
        }

        // 计算运费（根据配送方式和地址计算）
        BigDecimal deliveryFee = BigDecimal.ZERO; // 自提，免运费
        if ("local".equals(orderCreateDTO.getDeliveryType())) {
            // 同城配送，收取3元运费
            deliveryFee = BigDecimal.valueOf(3);
        }

        // 设置订单金额信息
        order.setGoodsAmount(goodsAmount);
        order.setDeliveryFee(deliveryFee);
        order.setDiscountAmount(discountAmount);
        order.setTotalAmount(goodsAmount.add(deliveryFee).subtract(discountAmount));

        // 设置配送方式
        order.setDeliveryType(orderCreateDTO.getDeliveryType());
        order.setRemark(orderCreateDTO.getRemark());

        // 设置配送备注（如果有）
        if (orderCreateDTO.getDeliveryNotes() != null && !orderCreateDTO.getDeliveryNotes().isEmpty()) {
            // 保存配送备注，以便后续创建配送记录时使用
            order.setDeliveryNotes(orderCreateDTO.getDeliveryNotes());
        }

        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        order.setCreatedAt(now);
        order.setUpdatedAt(now);

        // 保存订单
        ordersMapper.insert(order);

        // 打印订单ID，用于调试
        System.out.println("插入订单后获取的ID: " + order.getId());

        // 如果ID为空，尝试查询最新创建的订单
        if (order.getId() == null) {
            // 使用更精确的条件查询，确保获取到当前用户刚创建的订单
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Orders::getUserId, userId)
                    .eq(Orders::getOrderNo, order.getOrderNo())
                    .eq(Orders::getStoreId, order.getStoreId())
                    .eq(Orders::getAddressId, order.getAddressId())
                    .eq(Orders::getTotalAmount, order.getTotalAmount())
                    .eq(Orders::getDeliveryType, order.getDeliveryType())
                    .orderByDesc(Orders::getCreatedAt);

            // 添加时间范围限制，只查询最近30秒内创建的订单
            LocalDateTime thirtySecondsAgo = now.minusSeconds(30);
            queryWrapper.ge(Orders::getCreatedAt, thirtySecondsAgo);

            Orders latestOrder = ordersMapper.selectOne(queryWrapper);
            if (latestOrder != null) {
                order = latestOrder;
                System.out.println("通过查询获取的订单ID: " + order.getId());
            } else {
                throw new ObjectException("创建订单失败，无法获取订单ID");
            }
        }

        // 保存订单商品
        List<OrderItems> orderItemsList = new ArrayList<>();

        for (OrderItemVO itemVO : itemVOList) {
            OrderItems orderItem = getOrderItems(itemVO, order, now);

            orderItemsList.add(orderItem);
        }

        for (OrderItems orderItem : orderItemsList) {
            orderItemsMapper.insert(orderItem);
        }

        // 如果使用了优惠券，记录优惠券使用情况
        if (userCoupon != null) {
            boolean success = userCouponsService.useCoupon(userId, userCoupon.getId(), order.getId(),
                    order.getOrderNo());
            if (!success) {
                log.error("使用优惠券失败: userId={}, userCouponId={}, orderId={}", userId, userCoupon.getId(), order.getId());
                throw new ObjectException("使用优惠券失败，请稍后再试");
            }
        }

        // 如果是从购物车创建的订单，删除购物车中的商品
        if (!cartItemIds.isEmpty()) {
            LambdaQueryWrapper<CartItems> cartQueryWrapper = new LambdaQueryWrapper<>();
            cartQueryWrapper.eq(CartItems::getUserId, userId).in(CartItems::getId, cartItemIds);
            cartItemsMapper.delete(cartQueryWrapper);
        }

        // 跟踪哪些SKU已经被处理过，防止重复扣减
        Set<Integer> processedSkuIds = new HashSet<>();

        // 根据是否启用RabbitMQ选择不同的库存处理方式
        if (rabbitMqEnabled) {
            // 异步减少商品库存（通过消息队列）
            log.info("RabbitMQ已启用，开始异步处理订单商品库存扣减，商品数量: {}", itemVOList.size());

            for (OrderItemVO itemVO : itemVOList) {
                Integer skuId = itemVO.getSku().getId();

                // 防止重复扣减同一个SKU的库存
                if (processedSkuIds.contains(skuId)) {
                    log.warn("SKU: {} 已经被处理过，跳过重复扣减", skuId);
                    continue;
                }

                Integer quantity = itemVO.getQuantity();

                // 安全检查：防止异常大的数量
                if (quantity > 100) {
                    log.warn("异常大的订单数量，限制为最大100: skuId={}, 原始数量={}, 限制后数量=100",
                            skuId, quantity);
                    quantity = 100; // 设置合理的上限
                }

                log.info("发送库存扣减消息: skuId={}, 商品名称={}, 扣减数量={}",
                        skuId, itemVO.getProduct().getName(), quantity);

                // 构建库存变更消息
                InventoryChangeDTO inventoryChangeDTO = InventoryChangeDTO.builder()
                        .skuId(skuId)
                        .quantity(-quantity) // 负数表示减少库存
                        .orderId(order.getId())
                        .orderNo(order.getOrderNo())
                        .productName(itemVO.getProduct().getName())
                        .operationType(0) // 下单减库存
                        .remark("订单创建减库存")
                        .build();

                // 发送消息到库存减少队列
                rabbitTemplate.convertAndSend(
                        RabbitMQConfig.INVENTORY_EXCHANGE,
                        RabbitMQConfig.INVENTORY_DECREASE_ROUTING_KEY,
                        inventoryChangeDTO);

                // 标记此SKU已处理
                processedSkuIds.add(skuId);
            }
        } else {
            // 同步减少商品库存（直接数据库操作）
            log.info("RabbitMQ未启用，开始同步处理订单商品库存扣减，商品数量: {}", itemVOList.size());

            for (OrderItemVO itemVO : itemVOList) {
                Integer skuId = itemVO.getSku().getId();

                // 防止重复扣减同一个SKU的库存
                if (processedSkuIds.contains(skuId)) {
                    continue;
                }

                Integer quantity = itemVO.getQuantity();

                // 安全检查：防止异常大的数量
                if (quantity > 100) {
                    quantity = 100; // 设置合理的上限
                }

                log.info("开始同步扣减库存: skuId={}, 商品名称={}, 扣减数量={}",
                        skuId, itemVO.getProduct().getName(), quantity);

                if (!deductInventorySynchronously(skuId, quantity)) {
                    log.error("库存扣减失败, skuId: {}, quantity: {}", skuId, quantity);
                    throw new ObjectException("更新商品库存失败，请稍后再试");
                }

                // 标记此SKU已处理
                processedSkuIds.add(skuId);
            }
        }

        // 构建返回VO
        return getOrderDetail(userId, order.getId());
    }

    private static @NotNull OrderItems getOrderItems(OrderItemVO itemVO, Orders order, LocalDateTime now) {
        OrderItems orderItem = new OrderItems();
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(itemVO.getProduct().getId());
        orderItem.setProductName(itemVO.getProduct().getName());
        orderItem.setProductImage(itemVO.getProduct().getImage());
        orderItem.setSkuId(itemVO.getSku().getId());
        orderItem.setPrice(itemVO.getSku().getPrice());
        orderItem.setOriginalPrice(itemVO.getSku().getOriginalPrice());
        orderItem.setQuantity(itemVO.getQuantity());
        orderItem.setSpecifications(itemVO.getSku().getSpecs());
        orderItem.setSubtotal(itemVO.getSubtotal());
        orderItem.setReviewStatus(0); // 未评价
        orderItem.setCreatedAt(now);
        orderItem.setUpdatedAt(now);
        return orderItem;
    }

    @Override
    public PageResult<OrderVO> getOrdersByUserId(Integer userId, OrderPageQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId)
                .eq(StringUtils.hasText(queryDTO.getStatus()), Orders::getPayStatus, queryDTO.getStatus())
                .eq(StringUtils.hasText(queryDTO.getOrderNo()), Orders::getOrderNo, queryDTO.getOrderNo())
                .isNull(Orders::getDeleted)
                .ge(StringUtils.hasText(queryDTO.getStartTime()), Orders::getCreatedAt, queryDTO.getStartTime())
                .le(StringUtils.hasText(queryDTO.getEndTime()), Orders::getCreatedAt, queryDTO.getEndTime());

        // 如果有搜索关键词，需要查找所有可能匹配的订单项
        boolean hasKeywordSearch = StringUtils.hasText(queryDTO.getSearchKeyword());
        List<Integer> matchingOrderIds = new ArrayList<>();

        if (hasKeywordSearch) {
            String keyword = queryDTO.getSearchKeyword().trim().toLowerCase();

            // 1. 先查询订单号匹配的订单
            LambdaQueryWrapper<Orders> orderNoQueryWrapper = new LambdaQueryWrapper<>();
            orderNoQueryWrapper.eq(Orders::getUserId, userId)
                    .like(Orders::getOrderNo, keyword)
                    .isNull(Orders::getDeleted);
            List<Orders> orderNoMatches = ordersMapper.selectList(orderNoQueryWrapper);
            List<Integer> orderNoMatchIds = orderNoMatches.stream()
                    .map(order -> order.getId().intValue())
                    .toList();
            matchingOrderIds.addAll(orderNoMatchIds);

            // 2. 查询所有可能匹配商品名称或规格的订单项
            LambdaQueryWrapper<OrderItems> itemsQueryWrapper = new LambdaQueryWrapper<>();
            itemsQueryWrapper.like(OrderItems::getProductName, keyword)
                    .or()
                    .like(OrderItems::getSpecifications, keyword);

            // 获取匹配的订单ID列表
            List<OrderItems> matchingItems = orderItemsMapper.selectList(itemsQueryWrapper);
            List<Integer> matchingItemOrderIds = matchingItems.stream()
                    .map(item -> item.getOrderId().intValue()) // 确保类型转换为Integer
                    .distinct()
                    .toList();

            // 将匹配的订单ID添加到列表中
            matchingOrderIds.addAll(matchingItemOrderIds);

            // 3. 查询收货地址中包含关键词的地址
            LambdaQueryWrapper<Addresses> addressQueryWrapper = new LambdaQueryWrapper<>();
            addressQueryWrapper.eq(Addresses::getUserId, userId)
                    .and(wrapper -> wrapper
                            .like(Addresses::getRecipient, keyword)
                            .or()
                            .like(Addresses::getPhone, keyword)
                            .or()
                            .like(Addresses::getDetail, keyword));

            // 获取匹配的地址ID列表
            List<Addresses> matchingAddresses = addressesMapper.selectList(addressQueryWrapper);
            List<Integer> matchingAddressIds = matchingAddresses.stream()
                    .map(Addresses::getId)
                    .toList();

            // 如果找到匹配的地址，查询使用这些地址的订单
            if (!matchingAddressIds.isEmpty()) {
                LambdaQueryWrapper<Orders> addressOrderQueryWrapper = new LambdaQueryWrapper<>();
                addressOrderQueryWrapper.eq(Orders::getUserId, userId)
                        .in(Orders::getAddressId, matchingAddressIds)
                        .isNull(Orders::getDeleted);

                List<Orders> addressMatchingOrders = ordersMapper.selectList(addressOrderQueryWrapper);
                List<Integer> addressMatchingOrderIds = addressMatchingOrders.stream()
                        .map(order -> order.getId().intValue()) // 确保类型转换为Integer
                        .toList();

                // 将匹配的订单ID添加到列表中
                matchingOrderIds.addAll(addressMatchingOrderIds);
            }

            // 去重订单ID
            matchingOrderIds = matchingOrderIds.stream().distinct().collect(Collectors.toList());

            // 如果有匹配的订单ID，则使用这些ID进行查询
            if (!matchingOrderIds.isEmpty()) {
                // 重置查询条件，使用匹配的订单ID列表
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Orders::getUserId, userId)
                        .in(Orders::getId, matchingOrderIds)
                        .isNull(Orders::getDeleted)
                        .eq(StringUtils.hasText(queryDTO.getStatus()), Orders::getPayStatus, queryDTO.getStatus())
                        .ge(StringUtils.hasText(queryDTO.getStartTime()), Orders::getCreatedAt, queryDTO.getStartTime())
                        .le(StringUtils.hasText(queryDTO.getEndTime()), Orders::getCreatedAt, queryDTO.getEndTime());
            } else {
                // 如果没有匹配的订单，返回空结果
                PageResult<OrderVO> emptyResult = new PageResult<>();
                emptyResult.setItems(new ArrayList<>());
                emptyResult.setTotal(0L);
                return emptyResult;
            }
        }

        // 添加排序
        queryWrapper.orderByDesc(Orders::getCreatedAt);

        // 分页查询
        Page<Orders> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Orders> orderPage = ordersMapper.selectPage(page, queryWrapper);

        // 转换为VO
        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders order : orderPage.getRecords()) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            mapOrderStatus(order, orderVO);

            // 修正运费值 - 将0.1改为10，以保持一致性
            if (orderVO.getDeliveryFee() != null && orderVO.getDeliveryFee().compareTo(new BigDecimal("0.1")) == 0) {
                orderVO.setDeliveryFee(new BigDecimal("10"));
            }

            // 查询订单商品
            LambdaQueryWrapper<OrderItems> itemQueryWrapper = new LambdaQueryWrapper<>();
            itemQueryWrapper.eq(OrderItems::getOrderId, order.getId());
            List<OrderItems> orderItems = orderItemsMapper.selectList(itemQueryWrapper);

            List<OrderItemVO> itemVOList = orderItems.stream().map(item -> {
                OrderItemVO itemVO = new OrderItemVO();
                BeanUtils.copyProperties(item, itemVO);

                // 设置商品信息
                ProductSimpleVO productSimpleVO = new ProductSimpleVO();
                productSimpleVO.setId(item.getProductId());
                productSimpleVO.setName(item.getProductName());
                productSimpleVO.setImage(item.getProductImage());
                itemVO.setProduct(productSimpleVO);

                // 设置规格信息
                ProductSkuVO skuVO = new ProductSkuVO();
                skuVO.setId(item.getSkuId());
                skuVO.setSpecs(item.getSpecifications());
                skuVO.setPrice(item.getPrice());
                skuVO.setOriginalPrice(item.getOriginalPrice());
                itemVO.setSku(skuVO);

                return itemVO;
            }).collect(Collectors.toList());

            orderVO.setItems(itemVOList);

            // 查询地址信息
            Addresses address = addressesMapper.selectById(order.getAddressId());
            if (address != null) {
                AddressVO addressVO = new AddressVO();
                BeanUtils.copyProperties(address, addressVO);
                // 手动设置字段映射
                addressVO.setRecipientName(address.getRecipient());
                addressVO.setRecipientPhone(address.getPhone());
                addressVO.setDetailAddress(address.getDetail());
                orderVO.setAddress(addressVO);
            }

            // 设置时间格式
            if (order.getCreatedAt() != null) {
                orderVO.setCreatedAt(order.getCreatedAt());
            }
            if (order.getPaymentTime() != null) {
                orderVO.setPaymentTime(order.getPaymentTime());
            }
            if (order.getDeliveryTime() != null) {
                orderVO.setDeliveryTime(order.getDeliveryTime());
            }
            if (order.getCompletedTime() != null) {
                orderVO.setCompletedTime(order.getCompletedTime());
            }
            if (order.getCancelledTime() != null) {
                orderVO.setCancelledTime(order.getCancelledTime());
            }

            orderVOList.add(orderVO);
        }

        // 构建分页结果
        PageResult<OrderVO> pageResult = new PageResult<>();
        pageResult.setItems(orderVOList);
        pageResult.setTotal(orderPage.getTotal());

        return pageResult;
    }

    @Override
    public OrderVO getOrderDetail(Integer userId, Long orderId) {
        // 查询订单
        Orders order = baseMapper.selectById(orderId);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setReviewed(reviewsMapper.exists(new LambdaQueryWrapper<Reviews>().eq(Reviews::getOrderId, orderId)));

        // 修正运费值 - 将0.1改为10，以保持一致性
        if (orderVO.getDeliveryFee() != null && orderVO.getDeliveryFee().compareTo(new BigDecimal("0.1")) == 0) {
            orderVO.setDeliveryFee(new BigDecimal("10"));
        }

        // 设置订单状态
        mapOrderStatus(order, orderVO);

        // 查询订单商品
        LambdaQueryWrapper<OrderItems> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(OrderItems::getOrderId, order.getId());
        List<OrderItems> orderItems = orderItemsMapper.selectList(itemQueryWrapper);

        List<OrderItemVO> itemVOList = orderItems.stream().map(item -> {
            OrderItemVO itemVO = new OrderItemVO();
            BeanUtils.copyProperties(item, itemVO);

            // 设置商品信息
            ProductSimpleVO productSimpleVO = new ProductSimpleVO();
            productSimpleVO.setId(item.getProductId());
            productSimpleVO.setName(item.getProductName());
            productSimpleVO.setImage(item.getProductImage());
            itemVO.setProduct(productSimpleVO);

            // 设置规格信息
            ProductSkuVO skuVO = new ProductSkuVO();
            skuVO.setId(item.getSkuId());
            skuVO.setSpecs(item.getSpecifications());
            skuVO.setPrice(item.getPrice());
            skuVO.setOriginalPrice(item.getOriginalPrice());
            itemVO.setSku(skuVO);

            return itemVO;
        }).collect(Collectors.toList());

        orderVO.setItems(itemVOList);

        // 查询地址信息
        Addresses address = addressesMapper.selectById(order.getAddressId());
        if (address != null) {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(address, addressVO);
            // 手动设置字段映射
            addressVO.setRecipientName(address.getRecipient());
            addressVO.setRecipientPhone(address.getPhone());
            addressVO.setDetailAddress(address.getDetail());
            orderVO.setAddress(addressVO);
        }

        // 设置时间格式
        if (order.getCreatedAt() != null) {
            orderVO.setCreatedAt(order.getCreatedAt());
            // 添加字符串格式的创建时间
            orderVO.setCreatedAtStr(order.getCreatedAt().format(DATE_TIME_FORMATTER));
        }
        if (order.getPaymentTime() != null) {
            orderVO.setPaymentTime(order.getPaymentTime());
            orderVO.setPaymentTimeStr(order.getPaymentTime().format(DATE_TIME_FORMATTER));
        }
        if (order.getDeliveryTime() != null) {
            orderVO.setDeliveryTime(order.getDeliveryTime());
            orderVO.setDeliveryTimeStr(order.getDeliveryTime().format(DATE_TIME_FORMATTER));
        }
        if (order.getCompletedTime() != null) {
            orderVO.setCompletedTime(order.getCompletedTime());
            orderVO.setCompletedTimeStr(order.getCompletedTime().format(DATE_TIME_FORMATTER));
        }
        if (order.getCancelledTime() != null) {
            orderVO.setCancelledTime(order.getCancelledTime());
            orderVO.setCancelledTimeStr(order.getCancelledTime().format(DATE_TIME_FORMATTER));
        }

        return orderVO;
    }

    /**
     * 根据支付状态和订单状态映射到前端状态
     *
     * @param order   订单实体
     * @param orderVO 订单VO
     */
    @SuppressWarnings("null")
    private void mapOrderStatus(Orders order, OrderVO orderVO) {
        if (order != null) {
            Integer payStatus = order.getPayStatus();
            Integer orderStatus = order.getOrderStatus();
            // 将原始状态值复制到VO中
            orderVO.setPayStatus(payStatus);
            orderVO.setOrderStatus(orderStatus);

            // 首先检查订单是否已取消
            if (orderStatus != null && orderStatus == 5) {
                orderVO.setStatus("cancelled"); // 已取消状态优先
                return;
            }

            // 根据支付状态和订单状态映射到前端状态
            if (payStatus == 0) {
                orderVO.setStatus("pending"); // 待支付
            } else if (payStatus == 1) {
                if (orderStatus != null) {
                    if (orderStatus == 0 || orderStatus == 1 || orderStatus == 2) {
                        orderVO.setStatus("paid"); // 待发货
                    } else if (orderStatus == 3) {
                        orderVO.setStatus("shipping"); // 待收货/配送中
                    } else if (orderStatus == 6 && order.getDeliveryType().equals("self")) {
                        orderVO.setStatus("ready_for_pickup"); // 待自提
                    } else if (orderStatus == 6) {
                        orderVO.setStatus("delivered"); // 已送达待确认收货
                    } else if (orderStatus == 4) {
                        orderVO.setStatus("completed"); // 已完成
                    } else {
                        orderVO.setStatus("paid"); // 默认为已支付待发货
                    }
                }
            } else if (payStatus == 2) {
                orderVO.setStatus("refunded"); // 已退款
            } else {
                orderVO.setStatus("pending"); // 默认为待付款
            }
        }

    }

    /**
     * 生成订单编号
     *
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 订单编号规则：年月日时分秒 + 4位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomStr = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        return dateStr + randomStr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Integer userId, Integer orderId, String reason) {
        // 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 验证订单状态
        if (!(order.getPayStatus()).equals(0)) {
            throw new ObjectException("只有待付款的订单才能取消");
        }

        log.info("开始取消订单: orderId={}, orderNo={}, reason={}", orderId, order.getOrderNo(), reason);

        // 更新订单状态 - 同时更新orderStatus和payStatus
        order.setOrderStatus(5); // 5=cancelled
        // payStatus保持为0，表示此订单未支付且已取消
        order.setCancelReason(reason);
        order.setCancelledTime(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        // 检查订单是否使用了优惠券，如果是，则需要归还优惠券
        if (order.getCouponId() != null) {
            log.info("订单使用了优惠券，准备归还: orderId={}, couponId={}", orderId, order.getCouponId());
            returnCouponForCanceledOrder(userId, order);
        }

        // 查询订单商品
        LambdaQueryWrapper<OrderItems> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(OrderItems::getOrderId, orderId);
        List<OrderItems> orderItems = orderItemsMapper.selectList(itemQueryWrapper);

        // 根据是否启用RabbitMQ选择不同的库存处理方式
        if (rabbitMqEnabled) {
            // 异步恢复商品库存（通过消息队列）
            log.info("RabbitMQ已启用，订单包含{}个商品项，准备异步恢复库存", orderItems.size());

            // 跟踪哪些SKU已经被处理过，防止重复恢复
            Set<Integer> processedSkuIds = new HashSet<>();

            for (OrderItems item : orderItems) {
                Integer skuId = item.getSkuId();

                // 防止重复恢复同一个SKU的库存
                if (processedSkuIds.contains(skuId)) {
                    log.warn("SKU: {} 已经被处理过，跳过重复恢复", skuId);
                    continue;
                }

                Integer quantity = item.getQuantity();

                log.info("发送库存恢复消息: 商品={}, skuId={}, 数量={}", item.getProductName(), skuId, quantity);

                // 构建库存变更消息
                InventoryChangeDTO inventoryChangeDTO = InventoryChangeDTO.builder()
                        .skuId(skuId)
                        .quantity(quantity) // 正数表示增加库存
                        .orderId((long) orderId)
                        .orderNo(order.getOrderNo())
                        .productName(item.getProductName())
                        .operationType(1) // 取消订单加库存
                        .remark("订单取消恢复库存")
                        .build();

                // 发送消息到库存增加队列
                rabbitTemplate.convertAndSend(
                        RabbitMQConfig.INVENTORY_EXCHANGE,
                        RabbitMQConfig.INVENTORY_INCREASE_ROUTING_KEY,
                        inventoryChangeDTO);

                // 标记此SKU已处理
                processedSkuIds.add(skuId);
            }
        } else {
            // 同步恢复商品库存（直接数据库操作）
            log.info("RabbitMQ未启用，订单包含{}个商品项，准备同步恢复库存", orderItems.size());

            // 跟踪哪些SKU已经被处理过，防止重复恢复
            Set<Integer> processedSkuIds = new HashSet<>();

            for (OrderItems item : orderItems) {
                Integer skuId = item.getSkuId();

                // 防止重复恢复同一个SKU的库存
                if (processedSkuIds.contains(skuId)) {
                    continue;
                }

                Integer quantity = item.getQuantity();

                log.info("开始同步恢复库存: 商品={}, skuId={}, 数量={}", item.getProductName(), skuId, quantity);

                boolean updateSuccess = restoreInventorySynchronously(skuId, quantity);

                if (!updateSuccess) {
                    log.error("库存恢复失败, skuId: {}, quantity: {}", skuId, quantity);
                    // 这里不抛出异常，因为订单取消不应该因为库存恢复失败而失败
                    // 可以考虑记录日志或发送告警，后续人工处理
                }

                // 标记此SKU已处理
                processedSkuIds.add(skuId);
            }
        }

        boolean updated = ordersMapper.updateById(order) > 0;

        if (updated) {
            log.info("订单取消成功: orderId={}, orderNo={}", orderId, order.getOrderNo());
        } else {
            log.error("订单取消失败: orderId={}, orderNo={}", orderId, order.getOrderNo());
        }

        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeOrder(Integer userId, Integer orderId) {
        // 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 验证订单状态
        if (order.getPayStatus() != 1 || (order.getOrderStatus() != 3 && order.getOrderStatus() != 6)) {
            throw new ObjectException("只有配送中或已送达的订单才能确认收货");
        }

        // 更新订单状态
        order.setOrderStatus(4); // 已完成
        order.setCompletedTime(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        boolean updated = ordersMapper.updateById(order) > 0;

        if (updated) {
            // 更新会员积分和成长值
            try {
                membersService.updateMemberByOrderComplete(userId, orderId.longValue(), order.getTotalAmount());
                log.info("订单完成，已更新会员积分和成长值: userId={}, orderId={}", userId, orderId);
            } catch (Exception e) {
                log.error("更新会员积分和成长值失败: userId={}, orderId={}, error={}", userId, orderId, e.getMessage(), e);
                // 不影响主流程，继续执行
            }
        }

        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(Integer userId, Integer orderId) {
        // 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 验证订单状态，只有已完成或已取消的订单才能删除
        if (!(order.getOrderStatus().equals(4)) && !(order.getOrderStatus().equals(5))) {
            throw new ObjectException("只有已完成或已取消的订单才能删除");
        }

        // 逻辑删除订单（设置deleted字段为1）
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getId, orderId).set(Orders::getDeleted, 1).set(Orders::getUpdatedAt,
                LocalDateTime.now());

        return ordersMapper.update(null, updateWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Integer userId, Integer orderId, String paymentMethod) {
        log.info("订单支付: userId={}, orderId={}, paymentMethod={}", userId, orderId, paymentMethod);

        if (paymentMethod == null) {
            log.error("支付方式不能为空");
            throw new ObjectException("支付方式不能为空");
        }

        // 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            log.error("订单不存在或不属于当前用户: userId={}, orderId={}", userId, orderId);
            throw new ObjectException("订单不存在或不属于当前用户");
        }

        // 检查订单状态
        if (order.getPayStatus() != 0) {
            log.error("订单已支付或已取消，不能重复支付: orderId={}, payStatus={}", orderId, order.getPayStatus());
            throw new ObjectException("订单已支付或已取消，不能重复支付");
        }

        // 更新订单支付信息
        order.setPayStatus(1); // 已支付
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTime(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(order);

        if (result) {
            log.info("订单支付成功: orderId={}", orderId);

            // 根据配送方式处理后续流程
            if ("local".equals(order.getDeliveryType())) {
                // 同城配送，更新订单状态为待处理，等待商家准备好后再分配骑手
                order.setOrderStatus(2); // 已接单，等待商家准备
                updateById(order);
                log.info("同城配送订单状态更新为备货中: orderId={}", orderId);
            } else if ("self".equals(order.getDeliveryType())) {
                // 自提订单，更新订单状态为待处理
                order.setOrderStatus(2); // 已接单，等待商家准备
                updateById(order);
                log.info("自提订单状态更新为备货中: orderId={}", orderId);
            }
        } else {
            log.error("订单支付失败: orderId={}", orderId);
        }

        return result;
    }

    @Override
    public LogisticsTrackVO getOrderLogistics(Integer userId, Integer orderId) {
        // 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 查询物流信息
        LambdaQueryWrapper<Deliveries> deliveryQueryWrapper = new LambdaQueryWrapper<>();
        deliveryQueryWrapper.eq(Deliveries::getOrderId, orderId);
        Deliveries delivery = deliveriesMapper.selectOne(deliveryQueryWrapper);

        if (delivery == null) {
            throw new ObjectException("配送信息不存在");
        }

        // 查询收货地址
        Addresses addresses = addressesMapper.selectById(order.getAddressId());
        if (addresses == null) {
            throw new ObjectException("收货地址不存在");
        }

        // 组装返回数据
        LogisticsTrackVO logisticsTrackVO = new LogisticsTrackVO();
        logisticsTrackVO.setOrderId(orderId);
        logisticsTrackVO.setOrderNo(order.getOrderNo());
        // 设置骑手信息
        logisticsTrackVO.setRiderId(delivery.getRiderId());

        // 如果有骑手ID，查询骑手信息
        if (delivery.getRiderId() != null) {
            Riders rider = ridersService.getById(delivery.getRiderId());
            if (rider != null) {
                logisticsTrackVO.setRiderName(rider.getName());
                logisticsTrackVO.setRiderPhone(delivery.getRiderPhone());
            }
        }

        logisticsTrackVO.setEstimatedArrivalTime(
                delivery.getEstimatedArrivalTime() != null
                        ? delivery.getEstimatedArrivalTime().format(DATE_TIME_FORMATTER)
                        : null);

        // 转换状态
        String status = switch (delivery.getStatus()) {
            case 0 -> "待分配骑手";
            case 1 -> "配送中";
            case 2 -> "已送达";
            case 3 -> "配送异常";
            default -> "未知状态";
        };
        logisticsTrackVO.setStatus(status);

        // 设置地址信息
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(addresses, addressVO);
        addressVO.setCreatedAt(addresses.getCreatedAt().format(DATE_TIME_FORMATTER));
        addressVO.setRecipientPhone(addresses.getPhone());
        addressVO.setRecipientName(addresses.getRecipient());
        addressVO.setLatitude(addresses.getLatitude());
        addressVO.setLongitude(addresses.getLongitude());
        addressVO.setDetailAddress(addresses.getDetail());
        logisticsTrackVO.setAddress(addressVO);

        // 设置时间
        if (order.getDeliveryTime() != null) {
            logisticsTrackVO.setShippingTime(order.getDeliveryTime().format(DATE_TIME_FORMATTER));
        }
        if (delivery.getDeliveredAt() != null) {
            logisticsTrackVO.setDeliveredTime(delivery.getDeliveredAt().format(DATE_TIME_FORMATTER));
        }

        // 模拟轨迹数据（实际项目中可对接第三方物流API）
        List<LogisticsTrackVO.LogisticsTrackDetailVO> tracks = new ArrayList<>();

        // 已下单
        LogisticsTrackVO.LogisticsTrackDetailVO orderPlacedTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
        orderPlacedTrack.setTime(order.getCreatedAt().format(DATE_TIME_FORMATTER));
        orderPlacedTrack.setDescription("订单已下单");
        orderPlacedTrack.setLocation("用户端");
        orderPlacedTrack.setStatus("已下单");
        tracks.add(orderPlacedTrack);

        // 已支付
        if (order.getPaymentTime() != null) {
            LogisticsTrackVO.LogisticsTrackDetailVO paidTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
            paidTrack.setTime(order.getPaymentTime().format(DATE_TIME_FORMATTER));
            paidTrack.setDescription("订单已支付");
            paidTrack.setLocation("用户端");
            paidTrack.setStatus("已支付");
            tracks.add(paidTrack);
        }

        // 商家已接单
        if (order.getOrderStatus() >= 1) {
            LogisticsTrackVO.LogisticsTrackDetailVO acceptedTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
            acceptedTrack.setTime(order.getUpdatedAt().format(DATE_TIME_FORMATTER));
            acceptedTrack.setDescription("商家已接单，正在准备中");
            acceptedTrack.setLocation("商家端");
            acceptedTrack.setStatus("备货中");
            tracks.add(acceptedTrack);
        }

        // 已发货
        if (order.getDeliveryTime() != null) {
            LogisticsTrackVO.LogisticsTrackDetailVO shippingTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
            shippingTrack.setTime(order.getDeliveryTime().format(DATE_TIME_FORMATTER));
            shippingTrack.setDescription("骑手已取货，正在配送中");
            shippingTrack.setLocation("配送中");
            shippingTrack.setStatus("配送中");
            tracks.add(shippingTrack);
        }

        // 已送达
        if (delivery.getDeliveredAt() != null) {
            LogisticsTrackVO.LogisticsTrackDetailVO deliveredTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
            deliveredTrack.setTime(delivery.getDeliveredAt().format(DATE_TIME_FORMATTER));
            deliveredTrack.setDescription("订单已送达");
            deliveredTrack.setLocation(addresses.getDetail());
            deliveredTrack.setStatus("已送达");
            tracks.add(deliveredTrack);
        }

        // 已完成
        if (order.getCompletedTime() != null) {
            LogisticsTrackVO.LogisticsTrackDetailVO completedTrack = new LogisticsTrackVO.LogisticsTrackDetailVO();
            completedTrack.setTime(order.getCompletedTime().format(DATE_TIME_FORMATTER));
            completedTrack.setDescription("订单已完成");
            completedTrack.setLocation("用户端");
            completedTrack.setStatus("已完成");
            tracks.add(completedTrack);
        }

        logisticsTrackVO.setTracks(tracks);

        return logisticsTrackVO;
    }

    @Override
    public Map<String, Object> checkSkuStock(Integer skuId) {
        log.info("检查商品SKU库存: skuId={}", skuId);
        Map<String, Object> result = new HashMap<>();

        try {
            // 查询SKU信息
            ProductSku sku = productSkuMapper.selectById(skuId);

            if (sku == null) {
                result.put("success", false);
                result.put("message", "SKU不存在");
                return result;
            }

            // 查询商品信息
            Products product = productsMapper.selectById(sku.getProductId());

            // 构建结果
            result.put("success", true);
            result.put("skuId", sku.getId());
            result.put("skuCode", sku.getSkuCode());
            result.put("skuTitle", sku.getTitle());
            result.put("price", sku.getPrice());
            result.put("originalPrice", sku.getOriginalPrice());
            result.put("stock", sku.getStock());
            result.put("specs", sku.getSpecs());

            if (product != null) {
                result.put("productId", product.getId());
                result.put("productName", product.getName());
                result.put("productImage", product.getMainImage());
                result.put("categoryId", product.getCategoryId());
            }

        } catch (Exception e) {
            log.error("检查商品SKU库存异常: skuId={}, 错误: {}", skuId, e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询异常: " + e.getMessage());
        }

        return result;
    }

    /**
     * 为已取消的未支付订单归还优惠券
     *
     * @param userId 用户ID
     * @param order  订单信息
     */
    private void returnCouponForCanceledOrder(Integer userId, Orders order) {
        try {
            // 使用新的优惠券服务退还优惠券
            if (order.getCouponId() != null) {
                boolean success = userCouponsService.returnCoupon(userId, order.getId());
                if (success) {
                    log.info("优惠券退还成功: userId={}, orderId={}", userId, order.getId());
                } else {
                    log.warn("优惠券退还失败: userId={}, orderId={}", userId, order.getId());
                }
            }
        } catch (Exception e) {
            // 捕获异常但不抛出，避免影响订单取消流程
            log.error("归还优惠券过程中发生错误", e);
        }
    }

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void autoCancelUnpaidOrders() {
        log.info("开始执行自动取消未支付订单的定时任务，超时时间: {}分钟", AUTO_CANCEL_TIMEOUT_MINUTES);
        try {
            // 查询超时前创建且未支付的订单
            LocalDateTime cutoffTime = LocalDateTime.now().minusMinutes(AUTO_CANCEL_TIMEOUT_MINUTES);

            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Orders::getPayStatus, 0) // 未支付
                    .lt(Orders::getCreatedAt, cutoffTime) // 创建时间早于超时时间
                    .ne(Orders::getOrderStatus, 5); // 非已取消状态

            List<Orders> unpaidOrders = ordersMapper.selectList(queryWrapper);

            if (unpaidOrders.isEmpty()) {
                log.info("没有需要自动取消的订单");
                return;
            }

            log.info("找到{}个超时未支付订单，准备自动取消", unpaidOrders.size());

            for (Orders order : unpaidOrders) {
                try {
                    log.info("准备自动取消订单: ID={}, 订单号={}, 创建时间={}",
                            order.getId(), order.getOrderNo(),
                            order.getCreatedAt().format(DATE_TIME_FORMATTER));

                    // 直接更新订单状态，避免权限校验问题
                    // 设置订单状态为已取消
                    order.setOrderStatus(5); // 5=已取消
                    order.setCancelReason("系统自动取消：超过" + AUTO_CANCEL_TIMEOUT_MINUTES + "分钟未支付");
                    order.setCancelledTime(LocalDateTime.now());
                    order.setUpdatedAt(LocalDateTime.now());

                    // 更新订单
                    ordersMapper.updateById(order);

                    // 如果更新成功，恢复库存和优惠券
                    log.info("自动取消订单成功: 订单ID = {}, 订单编号 = {}", order.getId(), order.getOrderNo());

                    // 检查是否使用了优惠券，如果是，归还优惠券
                    if (order.getCouponId() != null) {
                        log.info("自动取消的订单使用了优惠券，准备归还: orderId={}, couponId={}",
                                order.getId(), order.getCouponId());
                        returnCouponForCanceledOrder(order.getUserId(), order);
                    }

                    // 获取订单商品
                    LambdaQueryWrapper<OrderItems> itemQueryWrapper = new LambdaQueryWrapper<>();
                    itemQueryWrapper.eq(OrderItems::getOrderId, order.getId());
                    List<OrderItems> orderItems = orderItemsMapper.selectList(itemQueryWrapper);

                    // 恢复库存
                    Set<Integer> processedSkuIds = new HashSet<>();
                    for (OrderItems item : orderItems) {
                        Integer skuId = item.getSkuId();

                        // 防止重复恢复同一个SKU的库存
                        if (processedSkuIds.contains(skuId)) {
                            continue;
                        }

                        Integer quantity = item.getQuantity();

                        // 同步恢复库存
                        restoreInventorySynchronously(skuId, quantity);

                        // 标记此SKU已处理
                        processedSkuIds.add(skuId);
                    }

                } catch (Exception ignored) {
                }
            }

        } catch (Exception ignored) {
        }
    }

    @Override
    public PageResult<OrderVO> getOrdersForAdmin(OrderPageQueryDTO queryDTO) {

        // 构建查询条件
        Page<Orders> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        // 按订单号查询
        if (StringUtils.hasText(queryDTO.getOrderNo())) {
            queryWrapper.like(Orders::getOrderNo, queryDTO.getOrderNo());
        }

        // 按状态查询
        if (StringUtils.hasText(queryDTO.getStatus())) {
            // 将状态字符串转换为对应的数字状态码
            if ("pending".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getPayStatus, 0);
            } else if ("paid".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getPayStatus, 1)
                        .eq(Orders::getOrderStatus, 0);
            } else if ("shipping".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getOrderStatus, 3);
            } else if ("delivered".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getOrderStatus, 6);
            } else if ("completed".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getOrderStatus, 4);
            } else if ("cancelled".equals(queryDTO.getStatus())) {
                queryWrapper.eq(Orders::getOrderStatus, 5);
            }
        }

        // 按时间范围查询
        if (StringUtils.hasText(queryDTO.getStartTime()) && StringUtils.hasText(queryDTO.getEndTime())) {
            queryWrapper.between(Orders::getCreatedAt, queryDTO.getStartTime(), queryDTO.getEndTime());
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Orders::getCreatedAt);

        // 执行分页查询
        Page<Orders> ordersPage = page(page, queryWrapper);

        // 转换为VO
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : ordersPage.getRecords()) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            // 设置订单状态文本
            mapOrderStatus(order, orderVO);

            // 查询订单项
            List<OrderItems> orderItems = orderItemsMapper.selectList(
                    new LambdaQueryWrapper<OrderItems>()
                            .eq(OrderItems::getOrderId, order.getId()));

            // 转换订单项为VO并填充商品详细信息
            List<OrderItemVO> orderItemVOList = new ArrayList<>();
            for (OrderItems item : orderItems) {
                OrderItemVO itemVO = new OrderItemVO();
                BeanUtils.copyProperties(item, itemVO);

                // 创建简单的产品对象
                if (item.getProductId() != null) {
                    Products product = productsMapper.selectById(item.getProductId());
                    if (product != null) {
                        ProductSimpleVO productSimpleVO = new ProductSimpleVO();
                        productSimpleVO.setId(product.getId());
                        productSimpleVO.setName(product.getName());
                        productSimpleVO.setImage(product.getMainImage());
                        productSimpleVO.setCategoryId(product.getCategoryId());
                        productSimpleVO.setBrandId(product.getBrandId());
                        itemVO.setProduct(productSimpleVO);
                    }
                }

                // 创建简单的规格对象
                if (item.getSkuId() != null) {
                    ProductSku sku = productSkuMapper.selectById(item.getSkuId());
                    if (sku != null) {
                        ProductSkuVO skuVO = getProductSkuVO(item, sku);
                        itemVO.setSku(skuVO);

                    }
                }

                orderItemVOList.add(itemVO);
            }

            // 设置订单项
            orderVO.setItems(orderItemVOList);

            // 查询并设置收货地址
            if (order.getAddressId() != null) {
                Addresses address = addressesMapper.selectById(order.getAddressId());
                if (address != null) {
                    AddressVO addressVO = new AddressVO();
                    BeanUtils.copyProperties(address, addressVO);
                    addressVO.setRecipientName(address.getRecipient());
                    addressVO.setRecipientPhone(address.getPhone());
                    addressVO.setDetailAddress(address.getDetail());
                    orderVO.setAddress(addressVO);
                }
            }

            orderVOList.add(orderVO);
        }

        // 构建分页结果
        PageResult<OrderVO> pageResult = new PageResult<>();
        pageResult.setItems(orderVOList);
        pageResult.setTotal(ordersPage.getTotal());

        return pageResult;
    }

    private static @NotNull ProductSkuVO getProductSkuVO(OrderItems item, ProductSku sku) {
        ProductSkuVO skuVO = new ProductSkuVO();
        skuVO.setId(sku.getId());
        skuVO.setProductId(sku.getProductId());
        skuVO.setSpecs(sku.getSpecs());
        skuVO.setPrice(sku.getPrice());
        skuVO.setSpecs(item.getSpecifications());
        skuVO.setStock(sku.getStock());
        skuVO.setSkuCode(sku.getSkuCode());
        skuVO.setSkuName(sku.getTitle());
        skuVO.setSkuImage(sku.getImages());
        skuVO.setOriginalPrice(sku.getOriginalPrice());
        return skuVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer autoAssignRider(Long orderId) {
        log.info("自动分配骑手: orderId={}", orderId);

        // 查询订单
        Orders order = getById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 确认订单配送方式
        if (!"local".equals(order.getDeliveryType())) {
            throw new ObjectException("只有同城配送订单才能分配骑手");
        }

        // 先检查是否已有配送记录
        LambdaQueryWrapper<Deliveries> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Deliveries::getOrderId, orderId);
        Deliveries existingDelivery = deliveriesMapper.selectOne(queryWrapper);

        // 调用骑手服务的自动分配方法
        Integer riderId = ridersService.autoAssignRider(orderId, order.getStoreId());

        if (riderId == null) {
            // 如果已有配送记录，更新为待分配状态
            if (existingDelivery != null
                    && (existingDelivery.getRiderId() == null || existingDelivery.getRiderId() != -1)) {
                existingDelivery.setRiderId(-1);
                existingDelivery.setStatus(0); // 待分配
                deliveriesMapper.updateById(existingDelivery);
            }
            return null;
        }

        // 如果已有配送记录，更新骑手信息
        if (existingDelivery != null) {
            existingDelivery.setRiderId(riderId);
            existingDelivery.setStatus(1); // 配送中

            // 查询骑手信息获取联系电话
            Riders rider = ridersService.getById(riderId);
            if (rider != null) {
                existingDelivery.setRiderPhone(rider.getPhone());
            }

            existingDelivery.setAssignedAt(LocalDateTime.now());
            // 更新预计送达时间
            existingDelivery.setEstimatedArrivalTime(LocalDateTime.now().plusMinutes(30));

            deliveriesMapper.updateById(existingDelivery);

            // 为骑手自动接单
            try {
                ridersService.acceptOrder(riderId, orderId);

            } catch (Exception ignored) {
            }
        }
        return riderId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmSelfPickup(Integer userId, Long orderId) {

        // 1. 查询订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId, orderId).eq(Orders::getUserId, userId);
        Orders order = ordersMapper.selectOne(queryWrapper);

        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 2. 确认订单配送方式
        if (!"self".equals(order.getDeliveryType())) {
            throw new ObjectException("只有自提订单才能确认自提");
        }

        // 3. 确认订单状态
        if (order.getOrderStatus() != 6) {
            throw new ObjectException("订单尚未准备好，无法确认自提");
        }

        // 4. 更新订单状态
        order.setOrderStatus(4); // 已完成
        order.setCompletedTime(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(order);

        if (result) {
            // 5. 更新配送记录
            LambdaQueryWrapper<Deliveries> deliveryQueryWrapper = new LambdaQueryWrapper<>();
            deliveryQueryWrapper.eq(Deliveries::getOrderId, orderId);

            Deliveries delivery = deliveriesMapper.selectOne(deliveryQueryWrapper);
            if (delivery != null) {
                delivery.setStatus(2); // 已完成
                delivery.setDeliveredAt(LocalDateTime.now());
                deliveriesMapper.updateById(delivery);
            }

            // 6. 更新会员积分和成长值
            try {
                membersService.updateMemberByOrderComplete(userId, orderId, order.getTotalAmount());
            } catch (Exception ignored) {
            }
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReadyForPickup(Long orderId) {
        log.info("商家确认自提单准备完成: orderId={}", orderId);

        // 1. 查询订单
        Orders order = getById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 2. 确认订单配送方式
        if (!"self".equals(order.getDeliveryType())) {
            throw new ObjectException("只有自提订单才能确认准备完成");
        }

        // 3. 确认订单状态
        if (order.getOrderStatus() > 2) {
            throw new ObjectException("订单状态不允许确认准备完成");
        }

        // 4. 更新订单状态
        order.setOrderStatus(6); // 已准备好，等待自提
        order.setUpdatedAt(LocalDateTime.now());

        boolean result = updateById(order);

        if (result) {

            // 5. 创建或更新配送记录
            LambdaQueryWrapper<Deliveries> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Deliveries::getOrderId, orderId);

            Deliveries delivery = deliveriesMapper.selectOne(queryWrapper);
            if (delivery == null) {
                // 创建新配送记录
                delivery = new Deliveries();
                delivery.setOrderId(orderId);
                delivery.setDeliveryType("self");
                delivery.setStatus(0); // 待自提
                delivery.setAssignedAt(LocalDateTime.now());
                deliveriesMapper.insert(delivery);
            } else {
                // 更新配送记录
                delivery.setStatus(0); // 待自提
                deliveriesMapper.updateById(delivery);
            }

            // 6. 发送用户通知
            // 实现通知功能，告知用户订单已准备好，可以前来自提
            NotificationWebSocketHandler.notifyOrderReadyForPickup(order.getUserId(), orderId, order.getOrderNo());
        }
        return result;
    }

    /**
     * 商家确认同城配送订单准备完成
     * 用于同城配送订单，商家确认订单已准备好，可以进行分配骑手
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmLocalOrderReady(Long orderId) {
        log.info("确认同城配送订单准备完成: orderId={}", orderId);

        // 1. 查询订单
        Orders order = getById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 2. 检查订单状态
        if (order.getOrderStatus() != 2) {
            throw new ObjectException("订单状态不允许此操作");
        }

        // 3. 检查配送方式
        if (!"local".equals(order.getDeliveryType())) {
            throw new ObjectException("非同城配送订单");
        }

        // 4. 更新订单发货 时间
        order.setUpdatedAt(LocalDateTime.now());
        order.setDeliveryTime(LocalDateTime.now()); // 设置发货时间

        boolean result = updateById(order);
        if (!result) {
            throw new ObjectException("更新订单状态失败");
        }

        // 5. 创建或更新配送记录
        DeliveryDTO deliveryDTO = new DeliveryDTO();
        deliveryDTO.setDeliveryType("local");
        boolean deliveryResult = createLocalDelivery(orderId, deliveryDTO);

        if (deliveryResult) {
            return true;
        } else {
            throw new ObjectException("配送记录创建/更新失败，请稍后重试");
        }
    }

    /**
     * 自动确认收货定时任务
     * 每天执行一次，自动确认超过指定天数的待收货订单
     */
    @Scheduled(cron = "0 0 3 * * ?") // 每天凌晨3点执行
    public void autoConfirmReceipt() {
        log.info("开始执行自动确认收货定时任务");

        try {
            // 查询需要自动确认收货的订单
            // 条件：已发货或已送达待确认（orderStatus=3或orderStatus=6）且发货时间超过AUTO_CONFIRM_RECEIPT_DAYS天
            LocalDateTime confirmTime = LocalDateTime.now().minusDays(AUTO_CONFIRM_RECEIPT_DAYS);

            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Orders::getOrderStatus, 3, 6) // 已发货或已送达待确认
                    .eq(Orders::getPayStatus, 1) // 已支付
                    .le(Orders::getUpdatedAt, confirmTime); // 更新时间超过N天

            List<Orders> orders = ordersMapper.selectList(queryWrapper);

            for (Orders order : orders) {
                try {

                    // 更新订单状态
                    order.setOrderStatus(4); // 已完成
                    order.setCompletedTime(LocalDateTime.now());
                    order.setUpdatedAt(LocalDateTime.now());
                    order.setRemark("系统自动确认收货：超过" + AUTO_CONFIRM_RECEIPT_DAYS + "天未手动确认");

                    // 更新订单
                    ordersMapper.updateById(order);

                    // 更新物流状态
                    LambdaQueryWrapper<Deliveries> deliveryQueryWrapper = new LambdaQueryWrapper<>();
                    deliveryQueryWrapper.eq(Deliveries::getOrderId, order.getId());

                    Deliveries delivery = deliveriesMapper.selectOne(deliveryQueryWrapper);
                    if (delivery != null) {
                        delivery.setStatus(2); // 2=已完成
                        delivery.setDeliveredAt(LocalDateTime.now());
                        deliveriesMapper.updateById(delivery);
                    }

                    // 更新会员积分和成长值
                    try {
                        membersService.updateMemberByOrderComplete(order.getUserId(), order.getId(),
                                order.getTotalAmount());
                    } catch (Exception ignored) {
                    }

                } catch (Exception ignored) {
                }
            }

        } catch (Exception ignored) {
        }
    }

    private boolean createLocalDelivery(Long orderId, DeliveryDTO deliveryDTO) {

        // 查询订单
        Orders order = baseMapper.selectById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 查询配送记录
        LambdaQueryWrapper<Deliveries> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Deliveries::getOrderId, orderId);
        Deliveries delivery = deliveriesMapper.selectOne(queryWrapper);

        // 从订单创建时保存的配送备注中获取
        String deliveryNotes = order.getRemark();

        if (delivery == null) {

            // 先确定骑手ID，再创建配送记录
            Integer riderId = null;

            // 如果指定了骑手ID，直接使用
            if (deliveryDTO.getRiderId() != null) {
                riderId = deliveryDTO.getRiderId();
            } else {
                // 没有指定骑手ID，先获取可用骑手ID，但不创建配送记录
                try {
                    // 注意：这里修改为只获取骑手ID，不创建配送记录
                    riderId = ridersService.getAvailableRider(order.getStoreId());
                } catch (Exception ignored) {
                }
            }

            // 创建配送记录
            delivery = new Deliveries();
            delivery.setOrderId(orderId);
            delivery.setDeliveryType(deliveryDTO.getDeliveryType());

            if (riderId != null && riderId > 0) {
                // 设置骑手信息
                delivery.setRiderId(riderId);
                delivery.setStatus(1); // 1=配送中

                // 查询骑手信息获取联系电话
                Riders rider = ridersService.getById(riderId);
                if (rider != null) {
                    delivery.setRiderPhone(rider.getPhone());
                }
                delivery.setAssignedAt(LocalDateTime.now());
                delivery.setPickedUpAt(LocalDateTime.now());
            } else {
                // 没有可用的骑手，设置一个临时骑手ID（后续会被更新）
                // 这样可以避免数据库约束错误
                delivery.setRiderId(-1); // 使用-1表示待分配
                delivery.setStatus(0); // 0=待分配骑手

                // 通过WebSocket发送通知给管理员
                try {
                    // 使用WebSocket通知管理员需要手动分配骑手
                    com.nnnu.wsnackshop.config.NotificationWebSocketHandler.notifyOrderNeedsRider(orderId,
                            order.getOrderNo());
                } catch (Exception e) {
                    log.error("发送WebSocket通知失败: {}", e.getMessage(), e);
                    // 继续执行，不影响主流程
                }
            }

            // 预计送达时间设置为当前时间后30分钟
            delivery.setEstimatedArrivalTime(LocalDateTime.now().plusMinutes(30));

            // 设置配送备注
            delivery.setDeliveryNotes(deliveryNotes);

            // 保存配送记录
            int result = deliveriesMapper.insert(delivery);
            if (result <= 0) {
                throw new ObjectException("创建配送记录失败");
            }

            log.info("成功创建新的配送记录: orderId={}, deliveryId={}, riderId={}",
                    orderId, delivery.getId(), delivery.getRiderId());

            // 自动为骑手接单（设置为已接单状态）
            if (riderId != null && riderId > 0) {
                try {
                    ridersService.acceptOrder(riderId, orderId);

                } catch (Exception e) {
                    log.error("系统自动接单异常: orderId={}, riderId={}, error={}",
                            orderId, riderId, e.getMessage(), e);
                    // 不抛出异常，不影响主流程
                }
            }
        } else {

            // 更新配送记录
            if (deliveryDTO.getRiderId() != null && !deliveryDTO.getRiderId().equals(delivery.getRiderId())) {
                // 如果指定了不同的骑手，更新骑手信息
                delivery.setRiderId(deliveryDTO.getRiderId());
                delivery.setStatus(1); // 1=配送中

                // 查询骑手信息获取联系电话
                Riders rider = ridersService.getById(deliveryDTO.getRiderId());
                if (rider != null) {
                    delivery.setRiderPhone(rider.getPhone());
                }
                delivery.setAssignedAt(LocalDateTime.now());

                // 更新预计送达时间
                delivery.setEstimatedArrivalTime(LocalDateTime.now().plusMinutes(30));
            } else if (delivery.getRiderId() == null || delivery.getRiderId() == -1) {
                // 如果之前没有分配骑手，尝试获取可用骑手
                Integer riderId = null;
                try {
                    // 获取可用骑手ID，但不创建配送记录
                    riderId = ridersService.getAvailableRider(order.getStoreId());
                } catch (Exception e) {
                    log.error("获取可用骑手失败: {}", e.getMessage(), e);
                }

                if (riderId != null && riderId > 0) {
                    delivery.setRiderId(riderId);
                    delivery.setStatus(1); // 1=配送中

                    // 查询骑手信息获取联系电话
                    Riders rider = ridersService.getById(riderId);
                    if (rider != null) {
                        delivery.setRiderPhone(rider.getPhone());
                    }
                    delivery.setAssignedAt(LocalDateTime.now());

                    // 更新预计送达时间
                    delivery.setEstimatedArrivalTime(LocalDateTime.now().plusMinutes(30));
                } else {
                    // 没有可用骑手，确保设置为-1
                    if (delivery.getRiderId() == null) {
                        delivery.setRiderId(-1);
                    }

                    // 通过WebSocket发送通知给管理员
                    try {
                        // 使用WebSocket通知管理员需要手动分配骑手
                        com.nnnu.wsnackshop.config.NotificationWebSocketHandler.notifyOrderNeedsRider(orderId,
                                order.getOrderNo());
                        log.info("已发送WebSocket通知，订单需要手动分配骑手: orderId={}, orderNo={}", orderId, order.getOrderNo());
                    } catch (Exception e) {
                        log.error("发送WebSocket通知失败: {}", e.getMessage(), e);
                        // 继续执行，不影响主流程
                    }
                }
            }

            // 如果配送备注为空，则设置配送备注
            if (StringUtils.hasText(deliveryNotes) && !StringUtils.hasText(delivery.getDeliveryNotes())) {
                delivery.setDeliveryNotes(deliveryNotes);
            }

            // 更新配送记录
            int result = deliveriesMapper.updateById(delivery);
            if (result <= 0) {
                log.error("更新配送记录失败: orderId={}", orderId);
                throw new ObjectException("更新配送记录失败");
            }

            log.info("成功更新配送记录: orderId={}, deliveryId={}", orderId, delivery.getId());

            // 为新分配的骑手自动接单
            if (deliveryDTO.getRiderId() != null && !deliveryDTO.getRiderId().equals(delivery.getRiderId())
                    && deliveryDTO.getRiderId() > 0) {
                try {
                    boolean acceptResult = ridersService.acceptOrder(deliveryDTO.getRiderId(), orderId);
                    if (acceptResult) {
                        log.info("系统自动接单成功: orderId={}, riderId={}", orderId, deliveryDTO.getRiderId());
                    } else {
                        log.warn("系统自动接单失败: orderId={}, riderId={}", orderId, deliveryDTO.getRiderId());
                    }
                } catch (Exception e) {
                    log.error("系统自动接单异常: orderId={}, riderId={}, error={}",
                            orderId, deliveryDTO.getRiderId(), e.getMessage(), e);
                    // 不抛出异常，不影响主流程
                }
            }
        }

        return true;
    }

    @Override
    public Map<String, Object> getRiderLocationByOrderId(Long orderId) {
        log.info("获取骑手位置信息: orderId={}", orderId);

        // 查询订单信息
        Orders order = getById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 查询配送信息
        LambdaQueryWrapper<Deliveries> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Deliveries::getOrderId, orderId);
        Deliveries delivery = deliveriesMapper.selectOne(queryWrapper);

        if (delivery == null || delivery.getRiderId() == null) {
            log.error("订单未分配骑手: orderId={}", orderId);
            throw new ObjectException("订单未分配骑手");
        }

        // 查询骑手信息
        Riders rider = ridersService.getById(delivery.getRiderId());
        if (rider == null) {
            log.error("骑手不存在: riderId={}", delivery.getRiderId());
            throw new ObjectException("骑手不存在");
        }

        // 构建结果
        Map<String, Object> result = new HashMap<>();

        // 模拟骑手位置信息（实际项目中应该从骑手的GPS定位系统获取）
        // 这里生成南宁市附近的随机位置
        double baseLatitude = 22.817; // 南宁市中心纬度
        double baseLongitude = 108.366; // 南宁市中心经度

        // 生成附近的随机位置（正负0.02度范围内，大约2-3公里范围）
        double randomLat = baseLatitude + (Math.random() * 0.04 - 0.02);
        double randomLng = baseLongitude + (Math.random() * 0.04 - 0.02);

        // 骑手位置信息
        Map<String, Object> location = new HashMap<>();
        location.put("latitude", randomLat);
        location.put("longitude", randomLng);
        location.put("accuracy", 10); // 精度10米
        location.put("speed", 15 + Math.random() * 10); // 速度15-25km/h
        location.put("updateTime", LocalDateTime.now().toString());

        // 骑手信息
        Map<String, Object> riderInfo = new HashMap<>();
        riderInfo.put("id", rider.getId());
        riderInfo.put("name", rider.getName());
        riderInfo.put("phone", rider.getPhone());

        result.put("location", location);
        result.put("rider", riderInfo);
        result.put("estimatedArrivalTime", delivery.getEstimatedArrivalTime());
        result.put("status", delivery.getStatus());

        return result;
    }

    @Override
    public Map<String, Object> getDeliveryInfoByOrderId(Long orderId) {
        log.info("获取订单配送信息: orderId={}", orderId);

        // 查询订单信息
        Orders order = getById(orderId);
        if (order == null) {
            throw new ObjectException("订单不存在");
        }

        // 查询配送信息
        LambdaQueryWrapper<Deliveries> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Deliveries::getOrderId, orderId);
        Deliveries delivery = deliveriesMapper.selectOne(queryWrapper);

        if (delivery == null) {
            log.error("订单配送信息不存在: orderId={}", orderId);
            throw new ObjectException("订单配送信息不存在");
        }

        // 构建结果
        Map<String, Object> result = new HashMap<>();

        // 配送基本信息
        result.put("id", delivery.getId());
        result.put("orderId", delivery.getOrderId());
        result.put("status", delivery.getStatus());
        result.put("deliveryType", delivery.getDeliveryType());
        result.put("estimatedArrivalTime", delivery.getEstimatedArrivalTime());
        result.put("assignedAt", delivery.getAssignedAt());
        result.put("pickedUpAt", delivery.getPickedUpAt());
        result.put("deliveredAt", delivery.getDeliveredAt());
        result.put("deliveryNotes", delivery.getDeliveryNotes());

        // 如果有骑手信息，添加骑手信息
        if (delivery.getRiderId() != null) {
            Riders rider = ridersService.getById(delivery.getRiderId());
            if (rider != null) {
                Map<String, Object> riderInfo = new HashMap<>();
                riderInfo.put("id", rider.getId());
                riderInfo.put("name", rider.getName());
                riderInfo.put("phone", rider.getPhone());
                result.put("rider", riderInfo);
            }
            result.put("riderPhone", delivery.getRiderPhone());
        }

        // 模拟配送轨迹 （实际项目中应该从数据库或轨迹服务中获取）
        List<Map<String, Object>> tracks = getMaps(delivery);

        result.put("tracks", tracks);

        return result;
    }

    private static @NotNull List<Map<String, Object>> getMaps(Deliveries delivery) {
        List<Map<String, Object>> tracks = new ArrayList<>();

        // 根据配送状态生成不同的轨迹
        if (delivery.getDeliveredAt() != null) {
            // 已送达
            Map<String, Object> track1 = new HashMap<>();
            track1.put("time", delivery.getDeliveredAt().toString());
            track1.put("description", "订单已送达");
            track1.put("location", "收货地址");
            tracks.add(track1);
        }

        if (delivery.getPickedUpAt() != null) {
            // 已取餐
            Map<String, Object> track2 = new HashMap<>();
            track2.put("time", delivery.getPickedUpAt().toString());
            track2.put("description", "骑手已取餐，正在配送中");
            track2.put("location", "商家地址");
            tracks.add(track2);
        }

        if (delivery.getAssignedAt() != null) {
            // 已分配骑手
            Map<String, Object> track3 = new HashMap<>();
            track3.put("time", delivery.getAssignedAt().toString());
            track3.put("description", "订单已分配骑手");
            track3.put("location", "系统");
            tracks.add(track3);
        }
        return tracks;
    }

    /**
     * 检查配送地址是否在配送范围内
     *
     * @param addressId 地址ID
     * @param storeId   店铺ID
     * @return true:在配送范围内 false:超出配送范围
     */
    private boolean isAddressInDeliveryRange(Integer addressId, Integer storeId) {
        // 获取地址信息
        Addresses address = addressesMapper.selectById(addressId);
        if (address == null || address.getLatitude() == null || address.getLongitude() == null) {
            log.error("地址不存在或地址未包含经纬度信息: addressId={}", addressId);
            return false;
        }

        // 获取店铺信息
        StoreAddresses store = storeAddressesMapper
                .selectOne(new LambdaQueryWrapper<StoreAddresses>().eq(StoreAddresses::getStoreId, storeId));
        if (store == null || store.getLatitude() == null || store.getLongitude() == null) {
            log.error("店铺不存在或店铺未包含经纬度信息: storeId={}", storeId);
            return false;
        }

        // 计算距离（米）
        double distance = calculateDistance(
                address.getLatitude(), address.getLongitude(),
                store.getLatitude(), store.getLongitude());

        // 判断是否在配送范围内（15公里）
        final double MAX_DELIVERY_DISTANCE = 15000; // 15公里（米）

        log.info("配送距离检查: addressId={}, storeId={}, distance={}, inRange={}",
                addressId, storeId, distance, distance <= MAX_DELIVERY_DISTANCE);

        return distance <= MAX_DELIVERY_DISTANCE;
    }

    /**
     * 计算两点之间的距离（米）
     * 使用Haversine公式计算球面距离
     */
    private double calculateDistance(Double lat1, Double lng1, Double lat2, Double lng2) {
        if (lat1 == null || lng1 == null || lat2 == null || lng2 == null) {
            return Double.MAX_VALUE; // 返回一个极大值表示无法计算
        }

        final double EARTH_RADIUS = 6378137; // 地球半径（米）

        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double latDiff = radLat1 - radLat2;
        double lngDiff = Math.toRadians(lng1) - Math.toRadians(lng2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(latDiff / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(lngDiff / 2), 2)));

        return s * EARTH_RADIUS;
    }

    @Override
    public int buyAgain(Integer userId, Long orderId) {
        log.info("再次购买订单商品: userId={}, orderId={}", userId, orderId);

        // 1. 获取订单信息，检查是否是当前用户的订单
        Orders order = getById(orderId);
        if (order == null) {
            log.error("订单不存在: orderId={}", orderId);
            throw new ObjectException("订单不存在");
        }

        if (!order.getUserId().equals(userId)) {
            log.error("无权访问他人订单: userId={}, orderId={}", userId, orderId);
            throw new ObjectException("无权访问此订单");
        }

        // 2. 获取订单中的所有商品
        LambdaQueryWrapper<OrderItems> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItems::getOrderId, orderId);
        List<OrderItems> orderItems = orderItemsMapper.selectList(queryWrapper);

        if (orderItems.isEmpty()) {
            log.warn("订单中没有商品: orderId={}", orderId);
            return 0;
        }

        // 从Spring容器中获取CartsMapper
        CartsMapper cartsMapper = applicationContext.getBean(CartsMapper.class);

        // 3. 获取用户的购物车ID
        LambdaQueryWrapper<Carts> cartQuery = new LambdaQueryWrapper<>();
        cartQuery.eq(Carts::getUserId, userId);
        Carts cart = cartsMapper.selectOne(cartQuery);

        if (cart == null) {
            // 如果用户没有购物车，则创建一个
            cart = new Carts();
            cart.setUserId(userId);
            cart.setUpdatedAt(LocalDateTime.now());
            cartsMapper.insert(cart);
        }

        int successCount = 0;

        // 4. 遍历订单商品，添加到购物车
        for (OrderItems item : orderItems) {
            try {
                // 先检查商品是否存在
                Products product = productsMapper.selectById(item.getProductId());
                if (product == null) {
                    log.warn("商品不存在: productId={}", item.getProductId());
                    continue;
                }

                // 检查规格是否存在
                ProductSku sku = productSkuMapper.selectById(item.getSkuId());
                if (sku == null || !sku.getSaleable() || sku.getStock() <= 0) {
                    log.warn("商品规格不存在或已下架或无库存: skuId={}", item.getSkuId());
                    continue;
                }

                // 检查购物车中是否已有相同商品
                LambdaQueryWrapper<CartItems> cartItemQuery = new LambdaQueryWrapper<>();
                cartItemQuery.eq(CartItems::getCartId, cart.getId())
                        .eq(CartItems::getProductId, item.getProductId())
                        .eq(CartItems::getSkuId, item.getSkuId());

                CartItems cartItem = cartItemsMapper.selectOne(cartItemQuery);

                if (cartItem != null) {
                    // 如果已存在，更新数量
                    cartItem.setQuantity(cartItem.getQuantity() + item.getQuantity());
                    cartItem.setUpdatedAt(LocalDateTime.now());
                    cartItemsMapper.updateById(cartItem);
                } else {
                    // 新增购物车商品
                    cartItem = new CartItems();
                    cartItem.setCartId(cart.getId());
                    cartItem.setUserId(userId);
                    cartItem.setProductId(item.getProductId());
                    cartItem.setSkuId(item.getSkuId());
                    cartItem.setQuantity(item.getQuantity());
                    cartItem.setSelected(1); // 默认选中
                    cartItem.setCreatedAt(LocalDateTime.now());
                    cartItem.setUpdatedAt(LocalDateTime.now());
                    cartItemsMapper.insert(cartItem);
                }

                successCount++;
            } catch (Exception e) {
                log.error("添加商品到购物车失败: orderId={}, productId={}, error={}",
                        orderId, item.getProductId(), e.getMessage());
            }
        }

        return successCount;
    }

}
